package com.bit.forum.exception;

import com.bit.forum.common.AppResult;
import com.bit.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 指定要处理的异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler (ApplicationException e){
        //打印异常信息
        e.printStackTrace();
        //打印日志
        log.error(e.getMessage());
        if (e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        //非空校验
        if (e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //返回具体的异常信息
        return AppResult.failed(e.getMessage());
    }


    /**
     * 处理未被捕获的异常
     * @param e
     * @return
     */
    @ExceptionHandler
    @ResponseBody
    public AppResult exceptionHandler(Exception e){
        //打印异常
        e.printStackTrace();
        //打印日志
        log.error(e.getMessage());
        if (e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return  AppResult.failed(e.getMessage());
    }
}
